import { FC, Fragment, useState } from 'react'
import MyHead from '../../components/MyHead'
import { useDispatch, useSelector } from 'react-redux'
import { App_userInfo, changeUserInfo } from '../../rtk/reducers/infoSilce'
import { Avatar, Button, Dialog, Form, Input, List, Mask, Radio, Space } from 'antd-mobile'
import { AudioOutline, ContentOutline, MailOutline, PhoneFill, PicturesOutline, SystemQRcodeOutline, UndoOutline, UserOutline, UserSetOutline } from "antd-mobile-icons"
import { changeUserInfoAPI, getInfoAPI } from '../../api/api'
import { reject } from 'lodash'
import { reg } from '../../utils/validate'
import QRCode  from 'qrcode.react';
import { CloseCircleOutline } from 'antd-mobile-icons'
import UploadFile from '../../components/UploadFile'
import { baseURL, imgUrl } from '../../api/request'

const MyInfo: FC = () => {
  const userInfo = useSelector(App_userInfo)
  const dispatch = useDispatch()
  const refreshData = async () => {
    let res: any = await getInfoAPI()
    if (res.code == "200") {
      dispatch(changeUserInfo(res.user))
    }
  }
  const [infoValue, setInfoValue] = useState<any>()
  const [form] = Form.useForm()
  const [qrCodeUrl,setQrCodeUrl] = useState<string>('')
  const [ visible, setVisible ] = useState<boolean>(false)


  // input框输入的值
  const onChange = (value: any) => {
    setInfoValue(value)
  }


  // 修改数据的input框
  const ShowMask = (title: any, key = '', value: any = '', type = '1') => {
    setInfoValue(value)
    let content: any

    // 加入type为 1 , 则显示input 反之显示复选框
    if (type == '1') {
      content = <Input onChange={onChange} style={{ border: '1px solid #ddd ', padding: 5, marginTop: 8 }} />
    } else {
      content = (
        <Radio.Group
          onChange={onChange}
        >
          <Space style={{ display: 'flex', justifyContent: 'center', marginTop: 8 }}>
            <Radio value='0'>男</Radio>
            <Radio value='1'>女</Radio>
          </Space>
        </Radio.Group>
      )
    }

    // 显示修改弹窗
    Dialog.confirm({
      title: "修改" + title,

      // content内容填充为Form表单
      content: <Form
        form={form}
        initialValues={ //表单内容初始值
          {
            [key]: value  //对应键名取值
          }
        }
      >
        <Form.Item
          name={key}
          rules={[
            {
              required: true,
              message: "内容不能为空"
            },
            key=="phonenumber"?{
              required:reg.phone,
              message:"手机号格式有误"
            }:{}
          ]}
        >
          {content}
        </Form.Item>
      </Form>,

      // Form组件的确认事件
      onConfirm: () => {
        // 表单校验
        form.validateFields()
        // 调用更新用户信息接口
          .then(async (value: any) => {
            let res: any = await changeUserInfoAPI({
              ...value
            })
            if (res.code == "200") {
              refreshData()
            }
          })
          .catch(err => {
            reject(err)
          })
      }
    })
  }


  // 头像上传
  const getUploadUrl = async(url:string)=>{
    console.log(url);

    let res:any = await changeUserInfoAPI({
      avatar:url
    })
    if(res.code == '200'){      
      refreshData()
    }
  }

  const AvatarContent = (
    <UploadFile getUploadUrl={getUploadUrl}>
        <Avatar style={{ borderRadius: '50%', margin: '5px 0' }} src={userInfo.avatar?  userInfo.avatar.replace(/public/,imgUrl) :''} />
    </UploadFile>
  )


  return (
    <div className='myinfo'>
      <MyHead title='个人信息' />
      <div className="myinfo-box" style={{ padding: 10 }}>
        {
          userInfo && <Fragment>
            <List header='个人隐私信息'>
              <List.Item prefix={<UserOutline />} extra={userInfo.userName}>
                用户名
              </List.Item>
              <List.Item prefix={<AudioOutline />} extra={userInfo.userId} >
                ID
              </List.Item>
              <List.Item prefix={<PicturesOutline />} extra={userInfo.nickName} onClick={() => ShowMask('昵称', 'nickName', userInfo.nickName, '1')}>
                昵称
              </List.Item>
              <List.Item prefix={<UserOutline />} extra={AvatarContent} onClick={()=>{}}>
                头像
              </List.Item>
              <List.Item prefix={<UserSetOutline />} extra={userInfo.sex == 0 ? "男" : "女"} onClick={() => ShowMask('性别', 'sex', userInfo.sex, '2')} >
                性别
              </List.Item>
              <List.Item prefix={<PhoneFill />} extra={userInfo.phonenumber} onClick={() => ShowMask('手机号', 'phonenumber', userInfo.phonenumber, '1')}>
                手机号
              </List.Item>
              <List.Item prefix={<MailOutline />} extra={userInfo.email} onClick={() => ShowMask('邮箱', 'email', userInfo.email, '1')}>
                邮箱
              </List.Item>
              <List.Item prefix={<ContentOutline />} extra={userInfo.idCard} onClick={() => ShowMask('身份证号', 'idCard', userInfo.idCard, '1')}>
                身份证号
              </List.Item>
              <List.Item prefix={<SystemQRcodeOutline />} onClick={ ()=>{
                setQrCodeUrl('君不见，走马川行雪海边，平沙莽莽黄入天'+userInfo.userId+'&userName='+userInfo.userName),
                setVisible(true)
              }}>
                我的二维码
              </List.Item>
            </List>
          </Fragment>
        }
        <div style={{ margin: 15 }}>
          <Button onClick={refreshData} color='primary' block>刷新个人信息<UndoOutline /></Button>
        </div>
      </div>
      <Mask visible={visible}>
        <div className="mask-box" style={{width:'100%', height:'100%', position:'relative', flexDirection:'column', display:'flex', justifyContent:'center', alignItems:'center'}}>
            <div className="qrcode" style={{width:'200px', height:'200px',borderRadius:10, position:'absolute', background:'white', display:'flex', justifyContent:'center', alignItems:'center'}}>
                <QRCode
                  id='bill_qr_code_url'
                  value={qrCodeUrl}   //value参数为生成二维码的链接
                  size={180}
                  fgColor="#000"  //二维码的颜色
                ></QRCode>
            </div>
          <CloseCircleOutline style={{position:'absolute',bottom:180,fontSize:32,color:"#fff"}}  onClick={()=>setVisible(false)}/>
        </div>
      </Mask>
    </div>
  )
}

export default MyInfo